<?php
declare (strict_types = 1);

namespace app\product\service;

use app\product\model\ProductSkuModel;

class ProductSkuService extends BaseService
{
    public function __construct(ProductSkuModel $productSkuModel)
    {
        $this->productSkuModel = $productSkuModel;
    }

    public function model(){
        return $this->productSkuModel;
    }

    public function list(array $where = [] , array $limit = [], array $sort= []){
        $limit = check_limit($limit);
        $sort = check_sort($sort);
        return $this->productSkuModel->where($where)->limit($limit['page'],$limit['pagesize'])->order($sort[0],$sort[1])->select();
    }

    public function select(array $where = [],$field = ['*']){
        return $this->productSkuModel->field($field)->where($where)->select();
    }

    public function count(array $where = []){
        return $this->productSkuModel->where($where)->count();
    }

    public function find(array $where = []){
        return $this->productSkuModel->where($where)->find();
    }

    public function insertGetId(array $data = []){
        return $this->productSkuModel->insertGetId($data);
    }

    public function update(array $where = [],array $data = []){
        return $this->productSkuModel->where($where)->update($data);
    }

    /**
     * 自定义生成系统产品sku
     * hd + 用户id + 6位数字
     */
    public function get_product_sku()
    {
        $data= array();
        $uid = request()->user_id;
        $data_info = $this->find(['uid'=>$uid]);
        if(empty($data_info))
        {
            $sku = 'hd'.$uid.'000001';
            $data['uid'] = $uid;
            $data['sku'] = $sku;
            $data['number'] = 1;
            $data['create_time'] = time();
            $this->insertGetId($data);
        }
        else
        {
            $sku = 'hd'.$uid.str_pad((string)$data_info['number'], 6, "0", STR_PAD_LEFT);
            $data['sku'] = $sku;
            $data['number'] = $data_info['number']+1;
            $data['update_time'] = time();
            $this->update(['uid'=>$uid],$data);
        }
        return trim($sku);
    }
}
